package com.jiang.mall.mallware.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiang.common.exception.NoStockException;
import com.jiang.common.to.mq.OrderTo;
import com.jiang.common.to.mq.StockDetailTo;
import com.jiang.common.to.mq.StockLockedTo;
import com.jiang.common.utils.PageUtils;
import com.jiang.common.utils.Query;
import com.jiang.common.utils.R;
import com.jiang.mall.mallware.ware.dao.WareSkuDao;
import com.jiang.mall.mallware.ware.entity.WareOrderTaskDetailEntity;
import com.jiang.mall.mallware.ware.entity.WareOrderTaskEntity;
import com.jiang.mall.mallware.ware.entity.WareSkuEntity;
import com.jiang.mall.mallware.ware.feign.OrderFeignService;
import com.jiang.mall.mallware.ware.feign.ProductFeignService;
import com.jiang.mall.mallware.ware.service.WareOrderTaskDetailService;
import com.jiang.mall.mallware.ware.service.WareSkuService;
import com.jiang.mall.mallware.ware.vo.OrderItemVo;
import com.jiang.mall.mallware.ware.vo.OrderVo;
import com.jiang.mall.mallware.ware.vo.WareSkuLockVo;
import com.rabbitmq.client.Channel;
import lombok.Data;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RabbitListener(queues = "stock.release.stock.queue")
@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    WareSkuDao wareSkuDao;
    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    OrderFeignService orderFeignService;
    @Autowired
    WareOrderTaskServiceImpl wareOrderTaskService;
    @Autowired
    WareOrderTaskDetailService wareOrderTaskDetailService;
    @Autowired
    RabbitTemplate rabbitTemplate;

    @RabbitHandler
    public void handleStocklockedRelease(StockLockedTo stockLockedTo, Message message, Channel channel) throws IOException {
        System.out.println("收到解锁库存的消息");
        StockDetailTo detail = stockLockedTo.getDetail();
        Long detailId = detail.getId();
        WareOrderTaskDetailEntity byId = wareOrderTaskDetailService.getById(detailId);
        if(byId != null) {
            Long id = stockLockedTo.getId(); // 库存工作单的id
            WareOrderTaskEntity orderTaskEntity = wareOrderTaskService.getById(id);
            String orderSn = orderTaskEntity.getOrderSn();
            R r = orderFeignService.getOrderStatus(orderSn);
            if(r.getCode() == 0) {
                OrderVo orderVo = r.getData("data", new TypeReference<OrderVo>(){});
                if(orderVo == null || orderVo.getStatus() == 4) {
                    // 订单不存在或订单取消，解锁库存
                    if(byId.getLockStatus() == 1) { // 已锁定配上已解锁，具体作用没想象出来
                        unlockSkuStock(detail.getSkuId(), detail.getWareId(), detail.getSkuNum(), detail.getId());
                    }
                    channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                }
            }else {
                // 远程服务调用失败的情况
                // 消息拒绝以后重新放到队列里，让别人继续消费解锁
                channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
            }
        }else {
            // 已经提前回滚了，在这里搜索不到
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }

    @RabbitHandler
    public void handleOrderCloseRelease(OrderTo orderTo, Message message, Channel channel) throws IOException {
        System.out.println("订单关闭准备解锁库存");
        try {
            unLockSkuStock(orderTo);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }catch (Exception e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }

    @Transactional
    void unLockSkuStock(OrderTo orderTo) {
        // 按照订单号找到库存工作单
        WareOrderTaskEntity orderSn = wareOrderTaskService.getOne(new QueryWrapper<WareOrderTaskEntity>().eq("order_sn", orderTo.getOrderSn()));
        List<WareOrderTaskDetailEntity> wareOrderTaskDetailEntities = wareOrderTaskDetailService.list(new QueryWrapper<WareOrderTaskDetailEntity>().eq("task_id", orderSn.getId()).eq("lock_status", 1));
        for (WareOrderTaskDetailEntity entity : wareOrderTaskDetailEntities) {
            unlockSkuStock(entity.getSkuId(), entity.getWareId(), entity.getSkuNum(), entity.getId());
        }
    }

    private void unlockSkuStock(Long skuId, Long wareId, Integer num, Long detailId) {
        // 库存解锁
        wareSkuDao.unLockSkuStock(skuId, wareId, num);
        // 更改库存工作单的状态
        WareOrderTaskDetailEntity wareOrderTaskDetailEntity = new WareOrderTaskDetailEntity();
        wareOrderTaskDetailEntity.setId(detailId);
        wareOrderTaskDetailEntity.setLockStatus(2);
        wareOrderTaskDetailService.updateById(wareOrderTaskDetailEntity);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                new QueryWrapper<WareSkuEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<WareSkuEntity> wrapper = new QueryWrapper<>();
        String skuId = (String) params.get("skuId");
        if (!StringUtils.isEmpty(skuId)) {
            wrapper.eq("sku_id", skuId);
        }
        String wareId = (String) params.get("wareId");
        if (!StringUtils.isEmpty(wareId)) {
            wrapper.eq("ware_id", wareId);
        }
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void addSocket(Long skuId, Long wareId, Integer skuNum) {
        //判断如果还没有库存记录，则为新增操作
        List<WareSkuEntity> wareSkuEntities = this.baseMapper.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
        if (wareSkuEntities != null && wareSkuEntities.size() > 0) {
            wareSkuDao.addSocket(skuId, wareId, skuNum);
        } else {
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setWareId(wareId);
            // 远程查询skuName的方法，如果失败，整个事务不需要回滚
            try {
                R info = productFeignService.info(skuId);
                if (info.getCode() == 0) {
                    Map<String, Object> data = (Map<String, Object>) info.get("skuInfo");
                    wareSkuEntity.setSkuName((String) data.get("skuName"));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            wareSkuDao.insert(wareSkuEntity);
        }
    }

    @Override
    public Map<Long, Boolean> getSkuHasStock(List<Long> skuIds) {

        Map<Long, Boolean> map = new HashMap<>();
        for (Long skuId : skuIds) {
            Long sumStock = wareSkuDao.selectSumStock(skuId);
            if (!(sumStock == null || new Long(0).equals(sumStock))) {
                map.put(skuId, true);
            } else {
                map.put(skuId, false);
            }
        }
//        List<Long> list =  skuIds.stream().filter(skuId ->
//            !(wareSkuDao.selectSumStock(skuId) == null || new Integer(0).equals(wareSkuDao.selectSumStock(skuId)))
//        ).collect(Collectors.toList());

        return map;
    }

    @Transactional(rollbackFor = NoStockException.class) // 默认只要是运行时异常都会回滚
    @Override
    public Boolean orderLockStock(WareSkuLockVo wareSkuLockVo) {
        /**
         * 保存库存工作单的详情
         */
        WareOrderTaskEntity wareOrderTaskEntity = new WareOrderTaskEntity();
        wareOrderTaskEntity.setOrderSn(wareSkuLockVo.getOrderSn());
        wareOrderTaskService.save(wareOrderTaskEntity);

        List<OrderItemVo> locks = wareSkuLockVo.getLocks();
        List<SkuWareHasStock> skuWareHasStocks = locks.stream().map(item -> {
            SkuWareHasStock skuWareHasStock = new SkuWareHasStock();
            Long skuId = item.getSkuId();
            skuWareHasStock.setSkuId(skuId);
            skuWareHasStock.setNum(item.getCount());
            // 查询这个商品在哪个仓库有库存
            List<Long> wareIds = wareSkuDao.listWareIdHasSkuStock(skuId);
            skuWareHasStock.setWareId(wareIds);
            return skuWareHasStock;
        }).collect(Collectors.toList());
        for (SkuWareHasStock skuWareHasStock : skuWareHasStocks) {
            Boolean skuStocked = false;
            Long skuId = skuWareHasStock.getSkuId();
            List<Long> wareIds = skuWareHasStock.getWareId();
            if(wareIds == null || wareIds.size() == 0) {
                throw new NoStockException(skuId);
            }
            for (Long wareId : wareIds)  {
                //  修改数据库 update 成功，返回 （修改的行数）1，失败返回 0。stock_lock表示多少商品正在被占用
                Long count = wareSkuDao.lockSkuStock(skuId, wareId, skuWareHasStock.getNum());
                if(count == 1) {
                    skuStocked = true;
                    // 告诉MQ库存锁定成功
                    WareOrderTaskDetailEntity wareOrderTaskDetailEntity = new WareOrderTaskDetailEntity(null, skuId , "", skuWareHasStock.getNum(), wareOrderTaskEntity.getId(), wareId, 1);
                    wareOrderTaskDetailService.save(wareOrderTaskDetailEntity);
                    StockLockedTo stockLockedTo = new StockLockedTo();
                    stockLockedTo.setId(wareOrderTaskEntity.getId());

                    StockDetailTo stockDetailTo = new StockDetailTo();
                    BeanUtils.copyProperties(wareOrderTaskDetailEntity, stockDetailTo);
                    stockLockedTo.setDetail(stockDetailTo);
                    rabbitTemplate.convertAndSend("stock-event-exchange", "stock.locked", stockLockedTo);
                    break;
                }else {
                    // 当前仓库没有库存，继续下一个仓库
                }
            }
            if (skuStocked == false) {
                // 当前商品在所有仓库都没有库存(没锁住)，有一个商品库存不够就全部商品都回滚！
                throw new NoStockException(skuId);
            }
        }
        return true;
    }

    @Data
    class SkuWareHasStock {
        private Long skuId;
        private Integer num;
        private List<Long> wareId;
    }
}